package com.demo.websocket.his;

import cn.hutool.json.JSONUtil;
import com.demo.websocket.vo.VteIpcMessageVO;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.WebSocket;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.net.URISyntaxException;

/**
 * websocket客户端
 */
@Slf4j
public class WebSocketClientConfig {

    public static WebSocketClient client;

    public static void main(String[] args) throws Exception {
        try {
            client = new WebSocketClient(new URI("ws://127.0.0.1:9005/websocketIpc/888"), new Draft_6455()) {
                @Override
                public void onOpen(ServerHandshake serverHandshake) {
                    log.info("打开链接");
                }

                @Override
                public void onMessage(String s) {
                    log.info("收到服务端返回消息" + s);
                }

                @Override
                public void onClose(int i, String s, boolean b) {
                    log.info("连接已关闭");
                }

                @Override
                public void onError(Exception e) {
                    e.printStackTrace();
                    log.info("发生错误已关闭");
                }
            };

            client.connect();
            while (!client.getReadyState().equals(WebSocket.READYSTATE.OPEN)) {
                log.info("未打开");
            }
            /**
             * {
             * 	code: "ce0bfd15059b68d67688884d7a3d3e8c",
             * 	ipc_id: "mx19110001",
             * 	ipc_mac: "08:00:20:0A:8C:6D",
             * 	ipc_model: "mx",
             * 	pat_ward: "ward id",
             * 	type:1,
             * 	time:20201029232200
             * }
             */
            VteIpcMessageVO sendData = new VteIpcMessageVO();
            sendData.setCode("ce0bfd15059b68d67688884d7a3d3e8c");
            sendData.setIpcId("mx19110001");
            sendData.setIpcMac("08:00:20:0A:8C:6D");
            sendData.setIpcModel("mx");
            sendData.setPatWard("11");
            sendData.setType(1);
            sendData.setTime(20201029232200L);

            String json = JSONUtil.toJsonStr(sendData);
            client.send(json);
            client.run();
            log.info("发送消息成功");
//            client.close();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

}
